//
//  MAHomeViewController.m
//  MateAdv
//
//  Created by 茶 on 2023/9/6.
//

#import "MAHomeViewController.h"
#import "MAAdvViewController.h"
#import "MADareInfoViewController.h"
#import "LoginViewController.h"

#import "MAMineViewController.h"
#import "MAVipViewController.h"

#import "MAHomeBtnView.h"
#import "MAHomeModel.h"
#import "MAPrivacyView.h"

#import "AppDelegate.h"
#import "MAUserModel.h"
#import <SAMKeychain.h>

@interface MAHomeViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) UIViewController *launchVC;

@end

@implementation MAHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (MAUserBool(kUserAgree)) {
        [self initDatasource];
        [self checkLogin];
    } else {
        [self initPrivaceView];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (!MAUserObj(kUserToken) && MAUserBool(kPrivacyShow)) {
        [self presentViewController:[LoginViewController new] animated:YES completion:nil];
    }
}

- (void)configLaunchView {
    if (kUserModel.vipStatus == 0 && !_launchVC) {
        _launchVC = [UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil].instantiateInitialViewController;
        [self addChildViewController:_launchVC];
        [self.view addSubview:_launchVC.view];
        [_launchVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        MAWeakify(self);
        [MAADManager sharedInstance].openClose = ^{
            MAStrongify(self);
            [self.launchVC.view removeFromSuperview];
            [self.launchVC removeFromParentViewController];
            self.launchVC = nil;
            [self initInterface];
        };
    }
}

- (void)removeLaunchView {
    [self.launchVC.view removeFromSuperview];
    [self.launchVC removeFromParentViewController];
    self.launchVC = nil;
}

- (void)initPrivaceView {
    [ReqManager requestBaseInfo];
    MAPrivacyView *view = [MAPrivacyView new];
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    MAWeakify(self);
    view.agreeBlock = ^{
        MAStrongify(self);
        [kUserDefaults setBool:YES forKey:kPrivacyShow];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kUserAgree];
        [((AppDelegate *)kAppDelegate) privacyAgreeEvent];
        [self checkLogin];
    };
}

- (void)initDatasource {
    MAWeakify(self);
    if (!MAUserObj(kSavedSwitch)) {
        [kUserDefaults setBool:YES forKey:kSavedSwitch];
    }
    [kUserDefaults setInteger:arc4random() % 30 + 1 forKey:kSavedData];
    if (!_launchVC) {
        [self configLaunchView];
    }
    [ReqManager fetchRuleWithSuccessed:^(id  _Nonnull object) {
        MAStrongify(self);
        [[NSUserDefaults standardUserDefaults] setObject:object forKey:kSavedRule];
        self.dataSource = [NSArray yy_modelArrayWithClass:MAHomeModel.class json:[object objectForKey:@"list"]];
        if (![MAADManager sharedInstance].isOpeningShow) {
            [self removeLaunchView];
            [self initInterface];
        } else if (!self->_launchVC) {
            [self initInterface];
        }
        
    } failed:^(NSError * _Nonnull error) {
        MAStrongify(self);
        [self.view hideToastActivity];
        NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:kSavedRule];
        if (dic) {
            self.dataSource = [NSArray yy_modelArrayWithClass:MAHomeModel.class json:[dic objectForKey:@"list"]];
            if (![MAADManager sharedInstance].isOpeningShow) {
                [self removeLaunchView];
                [self initInterface];
            } else if (!self->_launchVC) {
                [self initInterface];
            }
            
        } else {
            [LEEAlert alert].config
            .LeeTitle(@"网络请求错误")         // 添加一个标题 (默认样式)
            .LeeContent(@"是否重新加载")        // 添加一个标题 (默认样式)
            .LeeAction(@"取消", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
            })
            .LeeCancelAction(@"确定", ^{    // 添加一个取消类型的Action (默认样式 alert中为粗体 actionsheet中为最下方独立)
                MAStrongify(self);
                [self initDatasource];
            })
            .LeeShow();
        }
    }];
    
    [ReqManager requestBaseInfo];
}

- (void)checkLogin {
    if (!MAUserObj(kUserToken)) {
        MAWeakify(self);
        [self presentViewController:[LoginViewController new] animated:YES completion:^{
            MAStrongify(self);
            [self initDatasource];
        }];
    } else {
        [self initDatasource];
    }
}

- (void)initInterface {
    self.view.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:self.view.frame andColors:@[MAColor(@"#FF0071"), MAColor(@"#FF74B0")]];
    [self.view addSubview:self.scrollView];
    
    [self configNavBtn];
    
    UIView *contentView = [UIView new];
    [self.scrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.right.mas_equalTo(self.view);
    }];
    
    UIImageView *logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Home_Title"]];
    [contentView addSubview:logoView];
    [logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.ma_offset(23);
        make.top.ma_offset(8);
    }];
    
    NSMutableArray *btns = [NSMutableArray arrayWithCapacity:self.dataSource.count];
    for (int i = 0; i < self.dataSource.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i + 1;
        [contentView addSubview:button];
        MAHomeModel *model = _dataSource[i];
        if (model.type.intValue == 1) {
            MAHomeBtnView *view = [MAHomeBtnView new];
            view.model = model;
            view.backImgName = [NSString stringWithFormat:@"Home_%d", i];
            if (i == 1) {
                view.showDot = YES;
            }
            [button addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
        } else {
            [MAHomeBtnView initDareViewWithButton:button model:_dataSource[i]];
        }
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.ma_offset(22);
            make.right.ma_offset(-22);
            make.height.ma_offset(100);
            make.top.ma_offset(102 + (i * 118));
            if (i == 3) {
                make.bottom.mas_equalTo(0);
            }
        }];
        [btns addObject:button];
    }
    [self.view layoutIfNeeded];
    [[MAADManager sharedInstance] bannerAdEvent];
    [[MAADManager sharedInstance] fullScreenADEvent];
}

- (void)configNavBtn {
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Home_VIP"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(vipEvent)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Home_Me"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(mineEvent)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)buttonEvent:(UIButton *)button {
    MAHomeModel *model = [self.dataSource objectAtIndex:button.tag - 1];
    NSString *modelId = [NSString stringWithFormat:@"RuleAdMax_%@", model.identifier];
    if ([MAUserObj(modelId) intValue] > 0) {
        
    }
    if (model.isVip.intValue == 1 && kUserModel.vipStatus == 0) {
        MAWeakify(self);
        if (model.isAd.intValue == 1) {
            [LEEAlert alert].config
            .LeeClickBackgroundClose(YES)
            .LeeTitle(@"提示")         // 添加一个标题 (默认样式)
            .LeeContent(@"该模式有更具挑战性的任务，\n解锁会员或观看激励视频可获得更深入的体验")        // 添加一个标题 (默认样式)
            .LeeCancelAction(@"立即解锁", ^{    // 添加一个取消类型的Action (默认样式 alert中为粗体 actionsheet中为最下方独立)
                MAStrongify(self);
                [self vipEvent];
            })
            .LeeCancelAction(@"观看激励视频", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
            })
            .LeeAction(@"取消", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
            })
            .LeeShow();
        } else {
            [LEEAlert alert].config
            .LeeClickBackgroundClose(YES)
            .LeeTitle(@"提示")         // 添加一个标题 (默认样式)
            .LeeContent(@"该模式有更具挑战性的任务，\n解锁会员可获得更深入的体验")        // 添加一个标题 (默认样式)
            .LeeCancelAction(@"立即解锁", ^{    // 添加一个取消类型的Action (默认样式 alert中为粗体 actionsheet中为最下方独立)
                MAStrongify(self);
                [self vipEvent];
            })
            .LeeAction(@"取消", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
            })
            .LeeShow();
        }
    
        
    } else {
        if (model.type.intValue == 1) {
            MAAdvViewController *advVC = [MAAdvViewController new];
            advVC.model = model;
            [self.navigationController pushViewController:advVC animated:YES];
        } else if (model.type.intValue == 2) {
            MADareInfoViewController *dareVC = [MADareInfoViewController new];
            dareVC.model = model;
            [self.navigationController pushViewController:dareVC animated:YES];
        }
    }
    
}

- (void)vipEvent {
    [self.navigationController pushViewController:[MAVipViewController.class new] animated:YES];
}

- (void)mineEvent {
    [self.navigationController pushViewController:[MAMineViewController.class new] animated:YES];
}

- (UIScrollView *)scrollView {
    if (_scrollView) return _scrollView;
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    _scrollView.contentSize = self.view.bounds.size;
    return _scrollView;
}

@end
